package web;

import java.io.IOException;
import ctrl.Control;
import intf.AdHoc;
import intf.RunWindowsCmd;

public class Cache {

	static Control gui;
	
	public Cache(Control g) {
		gui = g;
	}
	
	public int currentWeb(String address) throws IOException {
		(new Thread(new caching(address))).start();
		return 0;

	}

	public class caching implements Runnable {
		String address;

		public caching(String a) {
			address = a;
		}

		public void run() {
			int returnCode = 0;
			String OS = System.getProperty("os.name").toLowerCase();

			if (OS.indexOf("mac") >= 0) {
				/* -O ; path
				 * -N0 Site-structure (default)
				 * -Y ; mirror ALL links located in the first level pages
				 * (mirror links) (--mirrorlinks)
				 * -w ; *mirror web sites (--mirror)
				 * n get non-html files 'near' an html file (ex: an image
				 * located outside) (--near)
				 * e go everywhere on the web (--go-everywhere)
				 * -r2 ; rN set the mirror depth to N (* r9999) (--depth[=N])
				 * -E60 ; EN maximum mirror time in seconds (60=1 minute, 3600=1
				 * hour) (--max-time[=N])
				 * -%c20 ; %cN maximum number of connections/seconds (*%c10)
				 * -m5000000 ;(5MB) mN maximum file length for a non-html file
				 * (--max-files[=N])
				 * 300000 bytes limit for HTML
				 */
				String cmd = "./src/script/httrack http://" + address + " -O ./cache/" + address
						+ " -N0 -Y -w -n -e -r1 -E60 -%c20 -m5000000,300000";
				returnCode = AdHoc.run(cmd);

			} else if (OS.indexOf("windows") >= 0) {
				
				try {
					new RunWindowsCmd ("httrack http://" + address + " -O ./cache/" + address
								+ " -N0 -Y -W -n -e -r1 -E60 -%c20 -m5000000,300000");
				} catch (Exception e) {
					returnCode = -1;
					System.out.println("@Cache - Exception windowscmd: " + e.getMessage());
				}	
					
			} else if (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0
					|| OS.indexOf("aix") > 0) {
				gui.println("System::Cache feature is not operational on this OS for this software version.");
				returnCode = -1;
			} else {
				System.out
						.println("Error 3217:-- Needs implementation in cache for current OS");
				returnCode = -1;
			}

			if (returnCode == 0)
			{
				gui.println("System::Done caching " + address);
				gui.getWeb().update();
				gui.println("System::Site Listing Refreshed.");
			}
			else if (returnCode == 133)
			{
				gui.println("System::Could not cache web site.");
				gui.println("System::HTTrack may need to be installed.");
			}
			else
				gui.println("System::Could not cache web site.");
			
			return;
		}
	}
}
